import serial
from binascii import unhexlify
import pymodbus.utilities as uti
import redis
import time
import statistics

if __name__ == '__main__':
    r = redis.Redis(db=0)
    r.set('radar_2', 'off')     # dmesg | grep tty

    ser = serial.Serial('/dev/ttyUSB4', 115200)
    ser.readline()

    distance_l = []

    while True:
        if r.get('radar_2').decode("utf-8") == 'on':
            result = ser.readline()
            if len(result) == 19:
                result = result[1:-2]

                checksum = result[-4:]
                data = result[:-4]

                if uti.computeCRC(unhexlify(data)) == int(checksum, 16):
                    distance = int(data[-4:], 16)

                    # distance_l.append(distance)
                    print(distance)

                    r.set('radar_2_distance', int(int(distance)*1.02))
                    # time.sleep(0.05)
                    # if len(distance_l) > 4:
                    #     # print(statistics.mean(distance_l))
                    #     # print(distance_l)
                    #     r.set('radar_2_distance', statistics.mean(distance_l))
                    #
                    #     distance_l = []

        else:
            time.sleep(0.5)
            distance_l = []

